package org.example.user.projects.dao;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 数据库链接管理器
 *
 * @author huangrz
 * @since 2021/3/3
 **/
public class DBConnectManager {

    private final static String URL = "jdbc:derby:/db/org.example.user-platform;create=true";

    public static final String CREATE_USERS_TABLE_DDL_SQL = "CREATE TABLE users(" +
            "id INT NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), " +
            "name VARCHAR(16) NOT NULL, " +
            "password VARCHAR(64) NOT NULL, " +
            "email VARCHAR(64) NOT NULL, " +
            "phoneNumber VARCHAR(64) NOT NULL" +
            ")";

    /**
     * 数据源
     */
    private DataSource dataSource;

    public static final String INSERT_ADMIN_DML_SQL = "insert into users(`name`, password, email, phoneNumber) " +
            "values('超级管理员', 'admin', 'admin@admin.com', '188xxxxx320')";

    /**
     * 初始化
     * @param dataSource
     */
    public void init(DataSource dataSource) {
        try {
            this.dataSource = dataSource;
            Connection connection = dataSource.getConnection();
            System.out.println("成功获取 connection："+connection);
            Statement statement = connection.createStatement();
            try {
                // 初始化创建表，并插入一条默认的超级管理员账号数据
                statement.execute(CREATE_USERS_TABLE_DDL_SQL);
                statement.execute(INSERT_ADMIN_DML_SQL);
            } catch (Exception e) {
                System.out.println("初始化创建表异常："+e.getMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取链接
     * @return
     * @throws SQLException
     */
    public Connection getConnection() throws SQLException {
        return this.dataSource.getConnection();
    }

    /**
     * 释放链接
     * @param connection
     */
    public void releaseConnection(Connection connection) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e.getCause());
            }
        }
    }

}
